#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json

import ConfigManage
import initLogger
import toolkit
from data_alchemy.account_book_alchemy import AccountBookAlchemy
from data_alchemy.account_voucher_alchemy import AccountVoucherAlchemy
from data_alchemy.balance_sheet_alchemy import BalanceSheetAlchemy
from init import TYPE_PROPERTY, TYPE_OWNERSHIP
import init


class AccountBook:

    def __init__(self, year=2022, month=1):
        '''
        函数功能：
        '''

        self.year = year
        self.month = month
        self.accountBookDetail = {}     #暂时未使用
        self.propertyIncrease = {}      #当月各科目资产增加情况
        self.propertyDecrease = {}      #当月各科目资产减少情况
        self.ownershipIncrease = {}     #当月各科目权属增加情况
        self.ownershipDecrease = {}     #当月各科目权属减少情况

        self.accountBookStartValue = {}  #当月初始化的账簿金额

    def getInitAccountBookValue(self):
        '''
        函数功能：获取账簿各科目月初的初始值
        :return:
        '''

        #获取上个月的账簿
        newYear, newMonth = toolkit.getLastMonthInt(self.year, self.month, 1)
        lastMonthAccountBookResult = self.getAccountBookDataMonthly(newYear, newMonth)

        if len(lastMonthAccountBookResult)==0:
            #处理没有找到账簿数据的情况，通常是处理初始时计算账簿时使用这个逻辑。
            self.getInitAccountBookValueTemp()
        else:
            for accountBookItem in lastMonthAccountBookResult:
                self.accountBookStartValue[accountBookItem.subject_name] = accountBookItem.end_value

            if self.month==1:
            #if self.month == 7:
                #处理1月份结转的特殊情况【处理转结】
                self.initFirstMonthForYearAccountBook(lastMonthAccountBookResult)


    def initFirstMonthForYearAccountBook(self, lastMonthAccountBookResult):
        '''
        函数功能：处理一月份转结时的记账【处理转结】
        :return:
        '''

        initLogger.logger.debug("call initFirstMonthForYearAccountBook function   处理上一年度资金转结")

        #计算上一年度的结余资金
        surplusLastYear = 0.0
        for accountBookItem in lastMonthAccountBookResult:
            if accountBookItem.subject_name.find("权属->自有->本年结余")!=-1:
                #匹配条件，将相关数值累加
                surplusLastYear = surplusLastYear + accountBookItem.end_value

        initLogger.logger.debug("上一年度结余资金为：%.2f"% surplusLastYear)

        #self.accountBookStartValue["权属->负债->蚂蚁花呗"] = 0.00
        #self.accountBookStartValue["权属->自有->追加资金"] = 0.00
        self.accountBookStartValue["权属->自有->历年积累"] = self.accountBookStartValue["权属->自有->历年积累"] + surplusLastYear

        ownershipStr = ConfigManage.readConfig("OWNERSHIP_NAME_JSON")
        ownershipInfoJson = json.loads(ownershipStr)

        earningDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["日常"]["收入"]
        expandDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["日常"]["支出"]
        investmentDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["投资"]
        # "权属->自有->本年结余->投资->

        # 对权属收入项进行年度初始化清零
        for earningItem in earningDic:
            subjectName = "权属->自有->本年结余->日常->收入->" + earningItem
            self.accountBookStartValue[subjectName] = 0.00

        # 对权属支出项进行年度初始化清零
        for expandItem in expandDic:
            subjectName = "权属->自有->本年结余->日常->支出->" + expandItem
            self.accountBookStartValue[subjectName] = 0.00

        # 对权属投资项进行年度初始化清零
        for investmentItem in investmentDic:
            subjectName = "权属->自有->本年结余->投资->" + investmentItem
            self.accountBookStartValue[subjectName] = 0.00





    def getInitAccountBookValueTemp(self):
        '''
        函数功能：获取账簿各科目月初的初始值【临时】
        :return:
        '''

        propertyStr = ConfigManage.readConfig("PROPERTY_NAME_JSON")
        propertyInfoJson = json.loads(propertyStr)


        bankDic = propertyInfoJson["资产"]["自有"]["货币"]["银行存款"]
        eCashDic = propertyInfoJson["资产"]["自有"]["货币"]["电子货币"]
        investmentDic = propertyInfoJson["资产"]["投资"]["理财"]
        stockDic = propertyInfoJson["资产"]["投资"]["股票"]

        for bankItem in bankDic:
            subjectName = "资产->自有->货币->银行存款->" + bankItem
            self.accountBookStartValue[subjectName] = 0.00

        for eCashItem in eCashDic:
            subjectName = "资产->自有->货币->电子货币->" + eCashItem
            self.accountBookStartValue[subjectName] = 0.00


        for investmentItem in investmentDic:
            subjectName = "资产->投资->理财->" + investmentItem
            self.accountBookStartValue[subjectName] = 0.00

        for stockItem in stockDic:
            subjectName = "资产->投资->股票->" + stockItem
            self.accountBookStartValue[subjectName] = 0.00

        self.accountBookStartValue["资产->自有->货币->兑换外汇"] = 0.00

        ownershipStr = ConfigManage.readConfig("OWNERSHIP_NAME_JSON")
        ownershipInfoJson = json.loads(ownershipStr)

        earningDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["日常"]["收入"]
        expandDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["日常"]["支出"]
        investmentDic = ownershipInfoJson["权属"]["自有"]["本年结余"]["投资"]
        debtDic = ownershipInfoJson["权属"]["负债"]
        # "权属->自有->本年结余->投资->

        # 对权属收入项进行年度初始化清零
        for earningItem in earningDic:
            subjectName = "权属->自有->本年结余->日常->收入->" + earningItem
            self.accountBookStartValue[subjectName] = 0.00

        # 对权属支出项进行年度初始化清零
        for expandItem in expandDic:
            subjectName = "权属->自有->本年结余->日常->支出->" + earningItem
            self.accountBookStartValue[subjectName] = 0.00

        # 对权属投资项进行年度初始化清零
        for investmentItem in investmentDic:
            subjectName = "权属->自有->本年结余->投资->" + investmentItem
            self.accountBookStartValue[subjectName] = 0.00

        # 对权属负债项进行年度初始化清零
        for debtItem in debtDic:
            subjectName = "权属->负债->" + debtItem
            self.accountBookStartValue[subjectName] = 0.00


        self.accountBookStartValue["权属->自有->追加资金"] = 0.00
        self.accountBookStartValue["权属->自有->历年积累"] = 0.00


        '''
        self.accountBookStartValue["权属->负债->蚂蚁花呗"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->收入->工资"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->收入->公积金"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->收入->补贴"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->食"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->住"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->行"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->家庭日常"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->学"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->上缴领导"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->刷卡消费"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->花呗消费"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->建行房贷"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->招行房贷"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->购买保险"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->日常->支出->金融手续费"] = 0.00
        self.accountBookStartValue["权属->自有->本年结余->投资->理财"] = 0.00
        '''


    def calculateAccountVoucherMonthly(self):
        '''
        函数功能：计算指定月的记账凭证数据
        :return:
        '''

        startDateStr, endDateStr = toolkit.monthlyChange(self.year, self.month)
        accountVoucher = AccountVoucherAlchemy()
        result = accountVoucher.SearchVoucherByDate(startDateStr, endDateStr)

        for i in range(len(result)):
            initLogger.logger.debug(i)
            dataRow = result[i]
            if (dataRow.ownership_increase_name=="权属->自有->历年积累"):
                self.processHistoryAccumulate(dataRow)
                continue


            if (dataRow.property_increase_name != ""):  #处理资产增加场景
                initLogger.logger.debug("property_increase_value=%f"%dataRow.property_increase_value)
                if (dataRow.property_increase_name in self.propertyIncrease):
                    self.propertyIncrease[dataRow.property_increase_name] = self.propertyIncrease[dataRow.property_increase_name] \
                                                                            + dataRow.property_increase_value
                else:
                    self.propertyIncrease[dataRow.property_increase_name] = dataRow.property_increase_value

                initLogger.logger.debug("propertyIncrease[%s]=%f"%(dataRow.property_increase_name, dataRow.property_increase_value))

            if (dataRow.property_decrease_name != ""): #处理资产减少场景
                initLogger.logger.debug("property_decrease_value=%f"%dataRow.property_decrease_value)
                if (dataRow.property_decrease_name in self.propertyDecrease):
                    self.propertyDecrease[dataRow.property_decrease_name] = self.propertyDecrease[dataRow.property_decrease_name] \
                                                                            + dataRow.property_decrease_value
                else:
                    self.propertyDecrease[dataRow.property_decrease_name] = dataRow.property_decrease_value
                initLogger.logger.debug("propertyDecrease[%s]=%f" % (dataRow.property_decrease_name, dataRow.property_decrease_value))


            if (dataRow.ownership_increase_name != ""):  #处理权属增加场景
                initLogger.logger.debug("ownership_increase_value=%f"%dataRow.ownership_increase_value)
                if (dataRow.ownership_increase_name in self.ownershipIncrease):
                    self.ownershipIncrease[dataRow.ownership_increase_name] = self.ownershipIncrease[dataRow.ownership_increase_name] + \
                                                                              dataRow.ownership_increase_value
                else:
                    self.ownershipIncrease[dataRow.ownership_increase_name] = dataRow.ownership_increase_value
                initLogger.logger.debug("ownershipIncrease[%s]=%f" % (dataRow.ownership_increase_name, dataRow.ownership_increase_value))

            if (dataRow.ownership_decrease_name != ""): #处理全需减少场景
                initLogger.logger.debug("ownership_decrease_value=%f"%dataRow.ownership_decrease_value)
                if (dataRow.ownership_decrease_name in self.ownershipDecrease):
                    self.ownershipDecrease[dataRow.ownership_decrease_name] = self.ownershipDecrease[dataRow.ownership_decrease_name] + \
                                                                              dataRow.ownership_decrease_value
                else:
                    self.ownershipDecrease[dataRow.ownership_decrease_name] = dataRow.ownership_decrease_value
                initLogger.logger.debug("ownershipDecrease[%s]=%f" % (dataRow.ownership_decrease_name, dataRow.ownership_decrease_value))




        initLogger.logger.debug(result)

    def processHistoryAccumulate(self, accountVoucherItem):
        '''
        函数功能：处理历史积累金额,
        :return:
        '''

        if (accountVoucherItem.property_increase_name != ""):  # 处理资产增加场景
            if (accountVoucherItem.property_increase_name in self.accountBookStartValue):
                self.accountBookStartValue[accountVoucherItem.property_increase_name] = self.accountBookStartValue[
                                                                            accountVoucherItem.property_increase_name] \
                                                                        + accountVoucherItem.property_increase_value
            else:
                self.accountBookStartValue[accountVoucherItem.property_increase_name] = accountVoucherItem.property_increase_value


        if (accountVoucherItem.ownership_increase_name != ""):  # 处理资产增加场景
            if (accountVoucherItem.ownership_increase_name in self.accountBookStartValue):
                self.accountBookStartValue[accountVoucherItem.ownership_increase_name] = self.accountBookStartValue[
                                                                            accountVoucherItem.ownership_increase_name] \
                                                                        + accountVoucherItem.ownership_increase_value
            else:
                self.accountBookStartValue[accountVoucherItem.ownership_increase_name] = accountVoucherItem.ownership_increase_value


        self.accountBookStartValue
    def genAccountBook(self):
        '''
        函数功能：用于生成新的账簿数据
        :return:
        '''

        #删除老的账簿数据
        accountBookAlchemy = AccountBookAlchemy()
        accountBookAlchemy.DelAccountBookByMonth(self.year, self.month)

        #生成新的账簿数据
        self.genPropertyAccountBook()
        self.genOwnershipAccountBook()

    def genOwnershipAccountBook(self):
        '''
        函数功能：生成权属账单信息
        :return:
        '''

        ownershipSubjectNameList = toolkit.genFullSubjectList(ConfigManage.readConfig("OWNERSHIP_NAME_JSON"))
        increaseValue = 0.0
        decreaseValue = 0.0
        startValue = 0.0
        endValue = 0.0

        for ownershipSubjectNameItem in ownershipSubjectNameList:
            if ownershipSubjectNameItem in self.ownershipIncrease:
                increaseValue = self.ownershipIncrease[ownershipSubjectNameItem]
            else:
                increaseValue = 0.0

            if ownershipSubjectNameItem in self.ownershipDecrease:
                decreaseValue = self.ownershipDecrease[ownershipSubjectNameItem]
            else:
                decreaseValue = 0.0

            if ownershipSubjectNameItem in self.accountBookStartValue:
                startValue = self.accountBookStartValue[ownershipSubjectNameItem]
            else:
                startValue = 0.0

            endValue = startValue + increaseValue - decreaseValue
            subjectNameList = toolkit.splitVoucher(ownershipSubjectNameItem)
            accountBookAlchemy = AccountBookAlchemy(year=self.year,
                                                    month=self.month,
                                                    accountType=TYPE_OWNERSHIP,
                                                    subjectName_0=subjectNameList[0],
                                                    subjectName_1=subjectNameList[1],
                                                    subjectName_2=subjectNameList[2],
                                                    subjectName_3=subjectNameList[3],
                                                    subjectName_4=subjectNameList[4],
                                                    subjectName_5=subjectNameList[5],
                                                    subjectName=ownershipSubjectNameItem,
                                                    startValue=startValue,  # 需要重新定义，补充实现
                                                    increaseValue=increaseValue,
                                                    decreaseValue=decreaseValue,
                                                    endValue=endValue
                                                    )

            accountBookAlchemy.AddAccountBookItem()

    def genPropertyAccountBook(self):
        '''
        函数功能：生成资产账单信息
        :return:
        '''

        propertySubjectNameList = toolkit.genFullSubjectList(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

        increaseValue = 0.0
        decreaseValue = 0.0
        startValue = 0.0
        endValue = 0.0

        for propertySubjectNameItem in propertySubjectNameList:
            if propertySubjectNameItem in self.propertyIncrease:
                increaseValue = self.propertyIncrease[propertySubjectNameItem]
            else:
                increaseValue = 0.0

            if propertySubjectNameItem in self.propertyDecrease:
                decreaseValue = self.propertyDecrease[propertySubjectNameItem]
            else:
                decreaseValue = 0.0

            if propertySubjectNameItem in self.accountBookStartValue:
                startValue = self.accountBookStartValue[propertySubjectNameItem]
            else:
                startValue = 0.0

            endValue = startValue + increaseValue - decreaseValue
            subjectNameList = toolkit.splitVoucher(propertySubjectNameItem)
            accountBookAlchemy = AccountBookAlchemy(year=self.year,
                                                    month=self.month,
                                                    accountType=TYPE_PROPERTY,
                                                    subjectName_0=subjectNameList[0],
                                                    subjectName_1=subjectNameList[1],
                                                    subjectName_2=subjectNameList[2],
                                                    subjectName_3=subjectNameList[3],
                                                    subjectName_4=subjectNameList[4],
                                                    subjectName_5=subjectNameList[5],
                                                    subjectName=propertySubjectNameItem,
                                                    startValue=startValue,  # 需要重新定义，补充实现
                                                    increaseValue=increaseValue,
                                                    decreaseValue=decreaseValue,
                                                    endValue=endValue
                                                    )

            accountBookAlchemy.AddAccountBookItem()


    def getAccountBookDataMonthly(self, year, month):
        '''
        函数功能：获取指定月份的账簿数据
        :param year:
        :param month:
        :return:
        '''


        accountBookAlchemy = AccountBookAlchemy()
        accountBookResult = accountBookAlchemy.SearchAccountBookByMonth(year, month)
        return accountBookResult


def main():


    accountBook = AccountBook(2022, 7)
    accountBook.getInitAccountBookValue()
    accountBook.calculateAccountVoucherMonthly()
    accountBook.genAccountBook()


if __name__ == '__main__':
    main()